package com.ald.crossex.service;

import com.ald.crossex.dao.CeCoreRoleDao;
import com.ald.crossex.dto.JqGridRequest;
import com.ald.crossex.entity.TCeCoreResource;
import com.ald.crossex.entity.TCeCoreRole;
import com.ald.crossex.util.JqGridFilterUtils;
import com.ald.crossex.util.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by lishijiong on 15/4/3.
 */
@Service
public class RoleService {

    @Autowired
    private CeCoreRoleDao roleDao;
    @Autowired
    private HibernateTemplate hibernateTemplate;


    /**
     * @param request
     * @return
     */
    public Page listRole(JqGridRequest request) {
        Page page = new Page(request.getPage(), request.getRows());

        String conditionSql = " where 1=1 ";

        if (StringUtils.isNotEmpty(request.getFilters())) {
            conditionSql += JqGridFilterUtils.convertJqGridFilter2String(request.getoFilters());
        }

        String orderSql = " order by " + (StringUtils.isEmpty(request.getSidx()) ? " rid " : request.getSidx()) + (StringUtils.isEmpty(request.getSord()) ? " asc " : request.getSord());

        List<TCeCoreRole> list = roleDao.queryPageByHQL("select  count(*) from TCeCoreRole o " + conditionSql, "from TCeCoreRole o" + conditionSql + orderSql, new Object[]{}, page);

        page.setDatas(list);

        return page;
    }

    @Transactional
    public void addRole(TCeCoreRole role) {
        role.setUpdateTime(new Date());
        role.setCreateTime(new Date());
        role.setBuiltin(2);//系统新增
        roleDao.create(role);
    }

    @Transactional
    public void updateRole(TCeCoreRole role) {

        TCeCoreRole r = roleDao.query(role.getRid());
        r.setUpdateTime(new Date());
        r.setRoleName(role.getRoleName());
        r.setRemark(role.getRemark());
        r.setOrgId(role.getOrgId());
        roleDao.update(r);

    }

    @Transactional
    public int delRole(String rid) throws Exception {
        try {
            String[] ids = rid.split(",");
            int i = 0;
            for (; i < ids.length; i++) {
                TCeCoreRole role = new TCeCoreRole();
                role.setRid(Integer.parseInt(ids[i]));
                roleDao.delete(role);
            }

            return i;

        } catch (Exception e) {
            throw new Exception("删除角色失败！");
        }

    }
}
